package com.sita.cfmoto.shouye;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.sita.cfmoto.R;
import com.sita.cfmoto.support.Constants;
import com.sita.cfmoto.support.GlobalContext;
import com.sita.cfmoto.utils.AMapUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class LocationSearchActivity extends AppCompatActivity {
    @Bind(R.id.poi_list)
    ListView poiList;
    @Bind(R.id.search_edit)
    EditText searchEdit;
    @Bind(R.id.search_cancel_btn)
    Button searchCancel;
    private LatLonPoint latLonPoint = AMapUtil.convertToLatLonPoint(Constants.DEFAULT_MAP_CENTER_LATLNG);
    private List<PoiItem> poiItems;// poi数据
    private List<String> poiItemData = new ArrayList<>();
    private ArrayAdapter adapter;
    private String city;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_location_poi);
        ButterKnife.bind(this);
        AMapLocation location = GlobalContext.getLocationClient().getLastKnownLocation();
        latLonPoint.setLatitude(location.getLatitude());
        latLonPoint.setLongitude(location.getLongitude());
        city = location.getCity();
        adapter = new ArrayAdapter<>(this, R.layout.item_poi_search, poiItemData);
        poiList.setAdapter(adapter);
        poiList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TextView listTxt = (TextView) view.findViewById(R.id.poi_search_listview_item);
                Intent intent = new Intent();
                intent.putExtra("location", listTxt.getText().toString());
                intent.putExtra("latLonPoint", poiItems.get(position).getLatLonPoint());
                setResult(1, intent);
                finish();
            }
        });
        doSearchQuery("", city, latLonPoint, adapter);
        searchCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchEdit.setText("");
                poiItemData.clear();
                doSearchQuery("", city, latLonPoint, adapter);
            }
        });
        searchEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                String location_key = searchEdit.getText().toString();
                doSearchQuery(location_key, "", null, adapter);
            }
        });

    }

    @OnClick({R.id.back_img})
    void onClickBack() {
        finish();
    }


    /**
     * 开始进行poi搜索
     */
    protected void doSearchQuery(String key, String city, LatLonPoint latLonPoint, final ArrayAdapter arrayadapter) {
        PoiSearch.Query query = new PoiSearch.Query(key, "", city);// 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
        query.setPageNum(0);
        query.setPageSize(20);
        PoiSearch poiSearch = new PoiSearch(this, query);
        poiSearch.setOnPoiSearchListener(new PoiSearch.OnPoiSearchListener() {
            @Override
            public void onPoiSearched(PoiResult result, int rCode) {
                if (rCode == 1000) {
                    if (result != null && result.getQuery() != null) {// 搜索poi的结果
                        if (result.getQuery().equals(query)) {// 是否是同一条
                            poiItems = result.getPois();// 取得第一页的poiitem数据，页数从数字0开始
                            poiItemData.clear();
                            for (int i = 0; i < poiItems.size(); i++) {
                                PoiItem poiItem = poiItems.get(i);
                                poiItemData.add(poiItem.getTitle());
                            }
                            arrayadapter.notifyDataSetChanged();
                        }
                    }
                }
            }

            @Override
            public void onPoiItemSearched(PoiItem poiItem, int i) {

            }
        });
        if (latLonPoint != null) {
            poiSearch.setBound(new PoiSearch.SearchBound(latLonPoint, 2000, true));//
            // 设置搜索区域为以lp点为圆心，其周围2000米范围
        }
        poiSearch.searchPOIAsyn();// 异步搜索
    }

//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            finish();
//        }
//        return super.onKeyDown(keyCode, event);
//    }
}
